#include "AlarmHandler.h"

AlarmHandler::AlarmHandler(const SocketStream * stream, Reactor * reactor, std::list<AlarmEntry> * entries)
  : reactor_(reactor), connection_(stream), entries_(entries)
{
  reactor_->registerHandler(this, READ_EVENT);
}

bool AlarmHandler::compareEntries(AlarmEntry one, AlarmEntry two)
{
  return (one.prio >= two.prio) ? true : false;
}

void AlarmHandler::handleEvent (Handle h, EventType et)
{
  if (et == READ_EVENT)
    {
      std::string received = (*connection_).recv();
      std::stringstream ss(received);
      std::string message;
      std::string prio;

      std::getline(ss, message, '\n');
      std::getline(ss, prio, '\n');

      std::istringstream iss(prio);
      
      AlarmEntry newEntry;
      
      newEntry.message = message;
      iss >> newEntry.prio;
      newEntry.time = time(NULL);

      while (entries_->size() >= 10)	
	  entries_->pop_front();
      
      entries_->push_back(newEntry);

      std::list<AlarmEntry> toPrint(*entries_);
      toPrint.sort(AlarmHandler::compareEntries);

      std::cout << "10 latest alarm events sorted on prio\n";
      for (std::list<AlarmEntry>::iterator it = toPrint.begin(); it != toPrint.end(); it++)
	std::cout << (*it).time << ": " << (*it).message << std::endl;
    }
}

Handle AlarmHandler::getHandle() const
{
  return connection_->getHandle();
}
